package cn.edu.gzu.controller;

import cn.edu.gzu.domain.User;
import cn.edu.gzu.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, User> redisTemplate;

    @PostMapping("/register")
    public String registerUser(HttpServletRequest request) {
        String name = request.getParameter("uname");
        String phone = request.getParameter("phonenum");
        String password = request.getParameter("pwd");

        // 添加用户到数据库
        User user = new User();
        user.setUsername(name);
        user.setPhoneNum(Integer.valueOf(phone));
        user.setPassword(password);

        userMapper.insert(user);

        // 在session中保存用户名
        HttpSession session = request.getSession();
        session.setAttribute("user", name);

        /*防止注入*/
        return "<script>alert('正在跳转后台界面!');window.location.href='/'</script>";
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestParam String phonenum, @RequestParam String password, HttpSession session) {
        // 1. 根据手机号从数据库中查询房东信息
        User byPhoneAndPwd = userMapper.getByPhoneAndPwd(phonenum, password);

        if (null == byPhoneAndPwd) {
            // 如果不存在，则返回登录失败
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }

        // 2. 如果存在，则生成一个唯一的 token，并将用户信息存储到 Redis 中
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token, byPhoneAndPwd);
        redisTemplate.expire(token, 30, TimeUnit.MINUTES); // 设置30分钟后过期

        // 3. 返回登录成功及生成的 token
        Map<String, String> data = new HashMap<>();
        data.put("token", token);

        return ResponseEntity.ok(data);

    }

}
